/**
 * Created by Lvyj on 2017/6/30 0030.
 */
/**
 * Created by CK on 2016/11/16.
 */
var list;
var markList;
var schoolId;
var DataGrid2  = new DataGridEvent();
$(document).ready(function(){
    list = $('#List');
    markList = $('#MarkList');
    $('.xh-datagrid-toolbar').parseToolbar();
    var lay = $('#lay_list');
    var refreshDom = $('#bt_List_Refresh');
    list.initDataGrid(moduleUrl + 'Server/getBoxList').setSelectThenEnable(['bt_List_EnableNotice', 'bt_List_DisableNotice'], ['bt_List_Change', 'bt_List_State', 'bt_MarkList_Add']);
    markList.initDataGrid();
    DataGrid.rowStyler = function(rowIndex, rowData){
        if (rowData.iSchoolId == 3563){
            return 'background-color: #9fd9ef;';
        }
    };
    DataGrid.onLoadSuccess = function(data){
        if(data['rows'].length <= 0) return false;
        schoolId = data['rows'][0].iSchoolId;
        markList.initDataGrid(moduleUrl + 'Server/getBoxMarkList', {"queryParams": {"iSchoolId": schoolId}}, DataGrid2)
            .setSelectThenEnable(['bt_MarkList_Del'], [], null, DataGrid2)
            .datagrid('getPanel').panel('setTitle', '盒子备注（' + data["rows"][0].sSchoolName + '）');
        var index = list.datagrid('getRowIndex', 3563);
        list.datagrid('freezeRow', index);
    };
    var clickTimer; //防止双击时触发单击事件
    //DataGrid.onDblClickRow = function(rowIndex, rowData){
    //    clearTimeout(clickTimer);
    //    schoolId = rowData.iSchoolId;
    //    if(lay.layout('panel', 'east')[0].clientWidth == 0){
    //        lay.layout('expand', 'east');
    //    }
    //    markList.addDataGridParams({"iSchoolId" : schoolId}).datagrid('getPanel').panel('setTitle', '盒子备注（' + rowData.sSchoolName + '）');
    //};
    DataGrid.onClickRow = function(rowIndex, rowData){
        clearTimeout(clickTimer);
        clickTimer = setTimeout(function() {
            //点击其他选项且已展开面板 则收起
            if(schoolId != rowData.iSchoolId && lay.layout('panel', 'east')[0].clientWidth != 0){
                lay.layout('collapse', 'east');
            }
        }, 300);
    };
    DataGrid.onDblClickCell = function(rowIndex, field, value){
        if(field == 'iPortNum' && refreshDom.length > 0){
            showChangePortPage();
        }
        else{
            clearTimeout(clickTimer);
            var rows = list.datagrid('getRows');
            var rowData = rows[rowIndex];
            schoolId = rowData.iSchoolId;
            if(lay.layout('panel', 'east')[0].clientWidth == 0){
                lay.layout('expand', 'east');
            }
            markList.addDataGridParams({"iSchoolId" : schoolId}).datagrid('getPanel').panel('setTitle', '盒子备注（' + rowData.sSchoolName + '）');
        }
    };
    $('#bt_List_Change').click(function(){
        if($(this).checkButtonDisabled()) return false;
        var newSchoolName = list.getDataGridSelectedField('sSchoolName');
        window.top.swal({
            title: newSchoolName,
            text: '是否确认切换？',
            type: 'question',
            showCancelButton: true,
            showCloseButton:true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: '切换',
            cancelButtonText: '取消',
            showLoaderOnConfirm: true,
            preConfirm: function () {
                return new Promise(function (resolve, reject) {
                    changeSchoolId();
                })
            }
        }).then(function(isConfirm) {
        }, function(dismiss) {});
        //xhExtra.showConfirm({title: '提示', content: '是否将公司盒子切换至<' + newSchoolName + '>？'}, changeSchoolId);
    });
    $('#bt_List_Rollback').click(function(){
        if($(this).checkButtonDisabled()) return false;
        window.top.swal({
            title: '是否确认还原？',
            type: 'question',
            showCancelButton: true,
            showCloseButton:true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: '还原',
            cancelButtonText: '取消',
            showLoaderOnConfirm: true,
            preConfirm: function () {
                return new Promise(function (resolve, reject) {
                    rollbackSchoolId();
                })
            }
        }).then(function(isConfirm) {
        }, function(dismiss) {});
        //xhExtra.showConfirm({title: '提示', content: '是否确认还原？'}, rollbackSchoolId);
    });
    refreshDom.click(function(){
        window.top.swal({
            title: '是否需要短信通知？',
            showCancelButton: true,
            cancelButtonText: '否',
            confirmButtonText: '是',
            preConfirm: function (port) {
                return new Promise(function (resolve, reject) {
                    if (port < 0) {
                        reject('端口号不正确！');
                    } else {
                        resolve();
                    }
                })
            },
            allowOutsideClick: false
        }).then(function(isConfirm) {
            list.addDataGridParams({refresh: true, notice: true});
        }, function(dismiss) {
            list.addDataGridParams({refresh: true});
        });
    });
    $('#bt_MarkList_Add').click(function(){
        if($(this).checkButtonDisabled()) return false;
        window.top.xhTop.showModal({
            title: '添加备注',
            content: '<textarea id="XHTool_BoolMark_sContent" class="form-control" rows="5"></textarea>',
            button: '保存'
        }, afterOpenMarkDiv);
    });
    $('#bt_MarkList_Del').click(function(){
        if($(this).checkButtonDisabled()) return false;
        var ids = markList.getDataGridSelectedFields('iBMId');
        xhExtra.showConfirm({title: 'Warning', content: '确认删除？'}, $.overtFun.confirmDel, {"_ids": ids, '_url': moduleUrl + 'Server/delBoxMark', "_list": markList});
    });
    $('#bt_List_State').click(function(){
        var src = moduleUrl + 'Server/showBoxState?iSchoolId=' + list.getDataGridSelectedField('iSchoolId');
        window.top.xhTop.showModal({
            title: '盒子状态<a id="bt_auto_refresh" class="btn btn-default btn-sm" style="margin-left: 20px;">自动刷新</a>',
            content: '<iframe frameborder="0" style="width: 100%;height: 600px;" src="'+ src +'"></iframe>',
            size: 'lg'
        });
    });
    $('#bt_List_EnableNotice').click(function(){
        if($(this).checkButtonDisabled()) return false;
        changeNoticeStatus(1);
    });
    $('#bt_List_DisableNotice').click(function(){
        if($(this).checkButtonDisabled()) return false;
        changeNoticeStatus(0);
    });
    //打开更改端口窗口
    function showChangePortPage()
    {
        schoolId = list.getDataGridSelectedField('iSchoolId');
        var schoolName = list.getDataGridSelectedField('sSchoolName');
        var oldPort = list.getDataGridSelectedField('iPortNum');
        window.top.swal({
            titleText: schoolName,
            input: 'number',
            inputValue: oldPort > 0 ? oldPort : '',
            inputPlaceholder: '端口号',
            inputAttributes: {style: 'max-width:200px;', min: 0},
            showCancelButton: true,
            cancelButtonText: '取消',
            confirmButtonText: '确认',
            showLoaderOnConfirm: true,
            preConfirm: function (port) {
                return new Promise(function (resolve, reject) {
                    if (port < 0) {
                        reject('端口号不正确！');
                    } else {
                        resolve();
                    }
                })
            },
            allowOutsideClick: false
        }).then(function (port) {
            $.post(moduleUrl + 'Server/changeBoxPort', {port: port, schoolId: schoolId}, function(result){
                if(result.error){
                    window.top.xhTop.showMessage({
                        type: 'error',
                        title: result.error
                    });
                    return false;
                }
                window.top.xhTop.showMessage({
                    type: 'success',
                    title: '提交成功！'
                });
                var index = list.datagrid('getRowIndex', result.iSchoolId);
                list.datagrid('updateRow', {index:index, row:{iPortNum: result.iPortNum}});
            }, 'json');
        }, function(dismiss) {});
    }
    //开启/关闭通知
    function changeNoticeStatus(notice)
    {
        schoolId = list.getDataGridSelectedField('iSchoolId');
        $.post(moduleUrl + 'Server/changeBoxNotice', {schoolId: schoolId, notice: notice}, function(result){
            if(result.error){
                window.top.xhTop.showMessage({
                    type: 'error',
                    title: result.error
                });
                return false;
            }
            window.top.xhTop.showMessage({
                type: 'success',
                title: (notice ? '开启' : '关闭') + '成功！'
            });
            var index = list.datagrid('getRowIndex', result.iSchoolId);
            list.datagrid('updateRow', {index:index, row:{bNotice: (result.bNotice == 1 ? '是' : '否')}});
        }, 'json');
    }
    //切换学校盒子
    function changeSchoolId() {
        var newSchoolId = list.getDataGridSelectedField('iSchoolId');
        if(!newSchoolId) return false;
        if(newSchoolId == 3563) return false;
        requestChangeBoxId(moduleUrl + 'Server/changeBoxId', {newSchoolId: newSchoolId});
    }
    //还原盒子
    function rollbackSchoolId() {
        requestChangeBoxId(moduleUrl + 'Server/rollbackBoxId', {});
    }
    //盒子切换网络请求
    function requestChangeBoxId(url, data)
    {
        $.ajax({
            url: url,
            type: 'POST',
            //async: false,
            data: data,
            success: function(result){
                window.top.xhTop.showMessage({
                    title: '10秒后自动刷新页面',
                    text: result,
                    type: 'success'
                });
                setTimeout(function(){
                    window.location.reload();
                }, 10000);
            },
            error: function(){
                window.top.xhTop.showMessage({
                    title: '操作失败！',
                    type: 'error'
                });
            }
        });
    }
});

function afterOpenMarkDiv(){
    $('#bt_Modal', window.top.document).click(function(){
        var content = $('#XHTool_BoolMark_sContent', window.top.document).val();
        if(!content){
            window.top.xhTop.showMessage({title: '内容不能为空！', type: 'error'});
            return false;
        }
        //var schoolId = list.getDataGridSelectedField('iSchoolId');
        $.post(moduleUrl + 'Server/addBoxMark', {iSchoolId: schoolId, sContent: content}, function(){
            $('#bt_Modal_Close', window.top.document).click();
            markList.dataGridReload();
        });
    });
    $('#XHTool_BoolMark_sContent', window.top.document).keydown(function(event) {
        if(event.keyCode == 13) {
            $('#bt_Modal', window.top.document).click();
        }
    });
}